<?php
/**
 * Created by PhpStorm.
 * User: lantranduc
 * Date: 5/22/14
 * Time: 11:10 AM
 */
App::uses('AppController', 'Controller');

class CaptchaController extends AppController{
    public $uses = false;




    public  function index(){
        if($this->Session->check('captcha')){
            $this->Session->delete('captcha');
        }
        $this->create_image();
    }



    public function create_image()
    {
        $md5_hash = md5(rand(0,999));
        $security_code = substr($md5_hash, 15, 6);
        $this->Session->write('captcha',$security_code);
        $width = 100;
        $height = 50;
        $image = ImageCreate($width, $height);
        $white = ImageColorAllocate($image, 255, 255, 255);
        $black = ImageColorAllocate($image, rand(0,255), rand(0,255), rand(0,255));
        ImageFill($image, 0, 0, $black);
        ImageString($image, 6, 25, 15, $security_code, $white);
        header("Content-Type: image/jpeg");
        ImageJpeg($image);
        ImageDestroy($image);
        die;
    }
    public function checkCaptcha($captcha,$local=1){
        if($this->Session->check('captcha')){
            if($captcha==$this->Session->read('captcha')){
                if($local){
                    $this->Session->delete('captcha');
                    return true;
                }else{
                    echo json_encode(array('status'=>'true'));
                    $this->Session->delete('captcha');
                    exit();
                }
            }
        }
        if($local){
            $this->Session->delete('captcha');
            return false;
        }else{
            echo json_encode(array('status'=>'false'));
            $this->Session->delete('captcha');
            exit();
        }

    }
}